#pragma once

#include "util.hpp"
#include "message.hpp"
#include "level.hpp"
#include <memory>
#include <vector>
#include <tuple>

namespace yd
{
    class format_item
    {
    public:
        using ptr = std::shared_ptr<format_item>;
        virtual ~format_item() {}
        virtual void format(std::ostream &os, const log_msg &msg) = 0;
    };
    class meg_format_item : public format_item
    {
    public:
        meg_format_item(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << msg._payload;
        }
    };
    class LevelFormatItem : public format_item
    {
    public:
        LevelFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << log_level::to_string(msg._level);
        }
    };
    class NameFormatItem : public format_item
    {
    public:
        NameFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << msg._name;
        }
    };
    class ThreadFormatItem : public format_item
    {
    public:
        ThreadFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << msg._tid;
        }
    };
    class TimeFormatItem : public format_item
    {
    private:
        std::string _format;

    public:
        TimeFormatItem(const std::string &format = "%H:%M:%S") : _format(format)
        {
            if (format.empty())
                _format = "%H:%M:%S";
        }
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            time_t t = msg._ctime;
            struct tm lt;
            localtime_r(&t, &lt);
            char tmp[128];
            strftime(tmp, 127, _format.c_str(), &lt);
            os << tmp;
        }
    };
    class CFileFormatItem : public format_item
    {
    public:
        CFileFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << msg._file;
        }
    };
    class CLineFormatItem : public format_item
    {
    public:
        CLineFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << msg._line;
        }
    };
    class TabFormatItem : public format_item
    {
    public:
        TabFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << "\t";
        }
    };
    class NLineFormatItem : public format_item
    {
    public:
        NLineFormatItem(const std::string &str = "") {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << "\n";
        }
    };
    class OtherFormatItem : public format_item
    {
    private:
        std::string _str;

    public:
        OtherFormatItem(const std::string &str = "") : _str(str) {}
        virtual void format(std::ostream &os, const log_msg &msg)
        {
            os << _str;
        }
    };
    class formatter
    {
        //按照用户指定的格式进行输出
        public:
        using ptr=std::shared_ptr<formatter>;
        formatter(const std::string &pattern="[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n")
        :_pattern(pattern)
        {
            parse_pattern();
        }
        const std::string pattern(){return _pattern;}
        std::string format(const log_msg &msg) {
            std::stringstream ss;
            for (auto &it : _items) {
                it->format(ss, msg);
            }
            return ss.str();
        }
        std::ostream& format(std::ostream &os, const log_msg &msg) {
            for (auto &it : _items) {
                it->format(os, msg);
            }
            return os;
        }
        format_item::ptr create_item(const std::string &fc, const std::string &subfmt)
        {
            if (fc == "m") return format_item::ptr(new meg_format_item (subfmt));
            if (fc == "p") return format_item::ptr(new LevelFormatItem(subfmt));
            if (fc == "c") return format_item::ptr(new NameFormatItem(subfmt));
            if (fc == "t") return format_item::ptr(new ThreadFormatItem(subfmt));
            if (fc == "n") return format_item::ptr(new NLineFormatItem(subfmt));
            if (fc == "d") return format_item::ptr(new TimeFormatItem(subfmt));
            if (fc == "f") return format_item::ptr(new CFileFormatItem(subfmt));
            if (fc == "l") return format_item::ptr(new CLineFormatItem(subfmt));
            if (fc == "T") return format_item::ptr(new TabFormatItem(subfmt));
            return format_item::ptr();
        }
        bool parse_pattern()
        {
            std::vector<std::tuple<std::string,std::string,int>>arry;
            std::string key;//存放%后的格式化字符
            std::string val;//存放格式化字符后面{}中子格式字符串
            std::string string_row;//存放非格式化字符
            bool sub_format_error=false;
            int pos=0;
            while(pos<_pattern.size())
            {
                if(_pattern[pos]!='%')
                {
                    string_row.append(1,_pattern[pos++]);
                    continue;
                }
                if(pos+1<_pattern.size()&&_pattern[pos+1]=='%')
                {
                    string_row.append(1,'%');
                    pos+=2;
                    continue;
                }
                if(string_row.empty()==false)
                {
                    arry.push_back(std::make_tuple(string_row,"",0));
                    string_row.clear();
                }
                pos+=1;
                if(pos<_pattern.size()&&isalpha(_pattern[pos]))
                {
                    key=_pattern[pos];
                }
                else
                {
                    std::cout<<"格式错误"<<std::endl;
                    return false;
                }
                pos+=1;
                if(pos<_pattern.size()&&_pattern[pos]=='{')
                {
                    sub_format_error=true;
                    pos+=1;
                    while(pos<_pattern.size())
                    {
                        if(_pattern[pos]=='}')
                        {
                            sub_format_error=false;
                            pos+=1;
                            break;
                        }
                        val.append(1,_pattern[pos++]);
                    }
                }
                arry.push_back(std::make_tuple(key,val,1));
                key.clear();
                val.clear();
            }
            if(sub_format_error)
            {
                std::cout<<"{}输入错误";
                return false;
            }
            if(string_row.empty()==false)arry.push_back(std::make_tuple(string_row,"",0));
            if(key.empty()==false)arry.push_back(std::make_tuple(key,val,1));
            for(auto&it:arry)
            {
                if(std::get<2>(it)==0)
                {
                    format_item::ptr fi(new OtherFormatItem(std::get<0>(it)));
                    _items.push_back(fi);
                }
                else
                {
                    format_item::ptr fi=create_item(std::get<0>(it),std::get<1>(it));
                    if (fi.get() == nullptr) {
                        std::cout << "没有对应的格式化字符: %" <<  std::get<0>(it) << std::endl;
                        return false;
                    }
                    _items.push_back(fi);
                }
            }
            return true;

        }
        private:
        std::string _pattern;
        std::vector<format_item::ptr> _items;
    };
}